<template>
  <el-dialog :title="title" :visible.sync="visible" width="950px" append-to-body>
    选择打印设备：<el-select v-model="printVal" placeholder="请选择" size="small">
                    <el-option
                      v-for="item in printEquips"
                      :key="item"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
    <el-button size="small" @click="print('true')">开始打印</el-button>
    <el-button size="small" @click="print('false')">打印预览</el-button>
    <el-divider></el-divider>
    <div id="pcon">
      <img v-if="printImg" :src="printImg" alt="" style="border: 1px solid #000;margin-bottom: 15px;">
    </div>
    <el-form ref="form" :model="form" :rules="rules" label-width="105px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="打印模板" prop="pageW">
            <el-select v-model="form.pageW" placeholder="请输入纸张宽度">
              <el-option
                v-for="dict in templateList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纸张宽度(mm)" prop="pageW">
            <el-input v-model="form.pageW" placeholder="请输入纸张宽度" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纸张高度(mm)" prop="pageH">
            <el-input v-model="form.pageH" placeholder="请输入纸张高度" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="二维码位置(x)" prop="codexy">
            <el-input v-model="form.codex" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="二维码位置(y)" prop="codexy">
            <el-input v-model="form.codey" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="二维码大小" prop="codeSize">
            <el-input v-model="form.codeSize" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文本位置x" prop="textX">
            <el-input v-model="form.textX" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文本位置y" prop="textY">
            <el-input v-model="form.textY" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文本间隔" prop="textLineheight">
            <el-input v-model="form.textLineheight" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="字体大小" prop="fontsize">
            <el-input v-model="form.fontsize" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>
<!--         <el-col :span="12">
          <el-form-item label="字体宽" prop="textW">
            <el-input v-model="form.textW" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="字体高" prop="textH">
            <el-input v-model="form.textH" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>-->
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
// import axios from 'axios'
import { getTemplateList } from "@/api/manage/fields";
let ws = null
const wslink = function (url, pack, onback) {
  if (ws == null) {
    ws = new WebSocket(url);
    ws.onback = onback;
    ws.onopen = function (evt) {
      ws.send(JSON.stringify(pack))
    };
    ws.onclose = function (evt) {
      ws = null
    };
    ws.onmessage = function (evt) {
      ws.onback(true, eval('(' + evt.data + ')'))
    };
    ws.onerror = function (evt) {
      ws.onback(false, evt)
    }
  } else {
    ws.onback = onback; ws.send(JSON.stringify(pack))
  }
}
export default {
  props: ['visible', 'title', 'assets'],
  data() {
    return {
      printEquips: [],
      filedSort: [
        {key: 'assetCode', value: '', name: '资产编号'},
        {key: 'assetName', value: '', name: '资产名称'},
/*        {key: 'brandName', value: '', name: '品牌'},
        {key: 'modelName', value: '', name: '型号'},
        {key: 'deptName', value: '', name: '使用部门'},*/
      ],
      form: {
        pageW: 70,
        pageH: 40,
        codex: 8,
        codey: 12.5,
        codeSize: 15,
        textX: 25,
        textY: 8,
        textLineheight: 5,
        textW: 50,
        textH: 30,
        fontsize: 8,
      },
      rules: {},
      printVal: null,
      printImg: '',
      templateList: [],
    }
  },
  watch: {
    visible(val) {
      if (val) {}
    }
  },
  mounted() {
    this.init()
    this.getTemplateList()
  },
  methods: {
    init() {
      this.callBackFunGetPrinter()
    },
    getTemplateList() {
      getTemplateList().then(response => {
        this.templateList = response.rows
      })
    },
    // 获取和选择打印机
    callBackFunGetPrinter() {
      let params = {
        command: '_thermal_enum_printer_',
        require: 'usb',
      }
      // axios.post('http://localhost:8008/thermal.io?data=', params, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
      //   console.log(res);
      //   let data = res.data
      //   if (data.code == 0) {
      //     this.printEquips = data.device
      //     this.printVal = data.device[0]
      //   }
      // })
      wslink('ws://127.0.0.1:8008/thermal.ws', params, (success, res) => {
        if (success) {
          console.log(res);
          let data = res
          if (data.code == 0) {
            this.printEquips = data.device
            this.printVal = data.device[0]
          }
        }
      })
    },
    //
    print(isPrint) {
      // this.assets.forEach(item => {
      //   this.printexec(item, isPrint)
      // })
      let assets = JSON.parse(JSON.stringify(this.assets))
      let row = assets.slice(0,1)[0]
      let success = true
      let timer = setInterval(async() => {
        if (!row) {
          console.log('全部打印完成');
          clearInterval(timer)
          return
        }
        if (success) {
          success = false
          success = await this.writeEPC(row)
          success = await this.printexec(row, isPrint)
          if (success) {
            assets.splice(0, 1)
            row = assets.slice(0,1)[0]
          } else {
            console.log(JSON.stringify(row))
            clearInterval(timer)
          }
        }
      }, 500)
    },
    // 打开打印机
    beginWork(port) {
      web_DSOpenPrinter(port, callBackFunOpenPrinter);
      let callBackFunOpenPrinter = (retVal) => {
        if (console) {
          console.log("打开打印机：" + retVal.RtnVal);
        }
        // printOpen = true;打开成功
        // this.assets.forEach(item => {
        //   this.writeEPC(item)
        // })
      }
      setTimeout(() => {
        this.assets.forEach(item => {
          this.writeEPC(item)
        })
      }, 1000)
    },
    // 写入epc
    writeEPC(row) {
      return new Promise((resolve, reject) => {
        let epc = row.rfidCode;
        console.log("状态正常，准备写入" + epc);
        let params = {
          command: '_thermal_cmd_engine_controler_',
          device: this.printVal,
          func: 'rfid_dynmic_write_epc',
          data: epc,
        }
        // axios.post('http://localhost:8008/thermal.io?data=', params, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
        //   console.log(res);
        //   let data = res.data
        //   if (data.code == 0) {
        //     resolve(true)
        //     // let staticepc = data.recv_data[6]+data.recv_data[7]+data.recv_data[8]+data.recv_data[9]
        //     // if(staticepc == "0000"){
        //     //   console.log('静态EPC写String成功：' + epc)
        //     //   console.log('注意静态检索标签后再读取静态epc')
        //     //   resolve(true)
        //     // }else{
        //     //   console.log('静态EPC写String失败返回：'+data.recv_data)
        //     //   reject(false)
        //     // }
        //   } else {
        //     reject(false)
        //   }
        // })
        wslink('ws://127.0.0.1:8008/thermal.ws', params, (success, res) => {
          if (success) {
            console.log(res);
            let data = res
            if (data.code == 0) {
              resolve(true)
              // let staticepc = data.recv_data[6]+data.recv_data[7]+data.recv_data[8]+data.recv_data[9]
              // if(staticepc == "0000"){
              //   console.log('静态EPC写String成功：' + epc)
              //   console.log('注意静态检索标签后再读取静态epc')
              //   resolve(true)
              // }else{
              //   console.log('静态EPC写String失败返回：'+data.recv_data)
              //   reject(false)
              // }
            } else {
              reject(false)
            }
          }
        })
      })
    },
    // 写入文本和二维码
    printexec(row, isPrint) {
      return new Promise((resolve, reject) => {
        let params = {
          command: '_thermal_zpl_draw_print_',
          device : this.printVal,
          printdirectly: isPrint,
          measurement_mode: 'mm',
          canvas_size: { "width": parseFloat(this.form.pageW), "height": parseFloat(this.form.pageH) },
          is_label: 'false',
          print  : [],
          get_base64_img: 'true'
        }
        //设置字体（需要系统存在的字体）
        params.print.push({ func: 'PDSetFont', szFontName: '宋体', fSize: parseFloat(this.form.fontsize) })

        //设置文本信息
        params.print.push({ func: 'PDSetTextDecorate', iIsLandScape: 1, iIsReverseSequence: 0, iIsAutoLineFeed: 0, iIsLayDown: 0 })

        //绘制文字
        // params.print.push({ func: 'PDDrawTextW', iX: 16, iY: 15, iWidth: 50, iHeight: 30, wszText: '姓 名: 王𪚥军' })
        this.filedSort.forEach((field,i) => {
          let text = field.name+'：'+row[field.key]
          params.print.push({ func: 'PDDrawTextW', iX: parseFloat(this.form.textX), iY: parseFloat(parseFloat(this.form.textY)+(parseFloat(this.form.textLineheight)*i)), iWidth: parseFloat(this.form.textW), iHeight: parseFloat(this.form.textH), wszText: text })
        })

        //绘制二维码
        params.print.push({ func: 'PDDrawQRCode', iX: parseFloat(this.form.codex), iY: parseFloat(this.form.codey), iWidth: parseFloat(this.form.codeSize), iHeight: parseFloat(this.form.codeSize), szData: row.rfidCode })

        // axios.post('http://localhost:8008/thermal.io?data=', params, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
        //   console.log(res);
        //   let data = res.data
        //   if (data.code == 0) {
        //     this.printImg = data.image_base64
        //     resolve(true)
        //   } else {
        //     reject(false)
        //   }
        // })
        wslink('ws://127.0.0.1:8008/thermal.ws', params, (success, res) => {
          if (success) {
            console.log(res);
            let data = res
            if (data.code == 0) {
              this.printImg = data.image_base64
              resolve(true)
            } else {
              reject(false)
            }
          }
        })
      })
    },
    // 写二维码
    printQrCode(XposQrCode,
                YposQrCode,
                sizeQrCode,
                textQrCode,
                byDarknessQrCode,//打印深度
                ErrLevelQrCode//容错级别)
    ) {
      web_DSZPLPrintQrCodeExA(0, parseInt(byDarknessQrCode), parseFloat(XposQrCode), parseFloat(YposQrCode), parseFloat(sizeQrCode), parseInt(ErrLevelQrCode), textQrCode);
    },
    // 写文本
    printText(byDarkness, dXPos, dYpos, widthSizeFont,heightSizeFont,content,font) {
      web_DSZPLPrintTextEx(0, font, false, false, parseFloat(byDarkness), parseFloat(dXPos), parseFloat(dYpos), parseFloat(heightSizeFont), parseFloat(widthSizeFont), content);
    },
  },
};
</script>

<style lang="scss" scoped></style>
